<?php
declare (strict_types = 1);

namespace app\controller\organization;

use app\BaseController;
use app\model\OrganizationRoles;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;

class Role extends BaseController
{
    /**
     * 获取角色模型
     * @return OrganizationRoles
     */
    private function model(): OrganizationRoles
    {
        return new OrganizationRoles();
    }

    /**
     * 显示角色列表
     * 传入组织ID
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $oid = $request->param('oid');
        try {
            $result = $this->model()->whereOr('oid', null)
                ->whereOr('oid', $oid)
                ->order('id', 'asc')
                ->select();
            return apiResponse(200, '成功', $result);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $data = $request->param();

        try {
            $this->validate($data,
                ['oid'=> 'require', 'name'=> 'require', 'slug'=> 'require'],
                ['oid.require'=> '请选择组织', 'name.require'=> '请输入角色名称', 'slug.require'=> '请输入角色标识']);
            //禁止创建admin/owner 标识
            if (in_array($data['slug'], ['admin', 'owner'])) {
                return apiResponse(400, '禁止创建admin/owner角色标识');
            }
            // 检查是否已存在相同的slug或name
            $this->model()->where('oid', $data['oid'])
                ->where(function ($query) use ($data) {
                    $query->whereOr('slug', $data['slug'])->whereOr('name', $data['name']);
                })
                ->findOrEmpty();
            if (!$this->model()->isEmpty()) {
                return apiResponse(400, '角色已存在,请勿重复添加');
            }
            $data['permissions'] = json_encode([]);
            $this->model()->create($data);
            return apiResponse(200, '角色添加成功');
        }catch (Exception $e){
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }
    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, int $id): Response
    {
        $data = $request->param();
        try {
            //检测角色是否存在
            $this->model()->where('id', $id)->findOrEmpty();
            if (!$this->model()->isEmpty()) {
                return apiResponse(400, '角色不存在');
            }
            //更新数据是否存在角色名称，如果存在则检测角色名称是否重复
            if(isset($data['name']) && $data['name']){
                $this->model()->where('oid', $data['oid'])
                    ->where(function ($query) use ($data) {
                        $query->whereOr('slug', $data['slug'])->whereOr('name', $data['name']);
                    })
                    ->findOrEmpty();
                if (!$this->model()->isEmpty()) {
                    return apiResponse(400, '角色已存在,请勿重复添加');
                }
            }
            if(isset($data['permissions']) && $data['permissions']){
                $this->model()->where('id', $id)->update(['permissions'=> json_encode($data['permissions'])]);
            }
            //更新数据
            $this->model()->where('id', $id)->update($data);
            return apiResponse(200, '角色更新成功');
        } catch (Exception $e) {
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return Response
     */
    public function delete(int $id): Response
    {
        try {
            //检测角色是否存在
            $this->model()->where('id', $id)->findOrEmpty();
            if (!$this->model()->isEmpty()) {
                return apiResponse(400, '角色不存在');
            }
            //删除角色
            $this->model()->where('id', $id)->delete();
            return apiResponse(200, '角色删除成功');
        } catch (Exception $e) {
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }
}